import { getCurrentUserId } from '@/utils/backend/auth'
import { prisma } from '@/utils/backend/db'
import { HttpStatus } from '@/utils/httpStatus'
import { NextResponse } from 'next/server'

// 处理好友请求（接受/拒绝）
export async function POST(req: Request) {
  try {
    const { requestId, operation } = await req.json()
    const token = req.headers.get('Authorization')?.replace('Bearer ', '')!
    const currentUserId = await getCurrentUserId(token)

    // 查找好友请求
    const friendRequest = await prisma.friendRequest.findFirst({
      where: {
        id: requestId,
        receiverId: currentUserId, // 确保只能处理发给自己的请求
        status: 'pending' // 只能处理待处理的请求
      }
    })

    if (!friendRequest) {
      return NextResponse.json({
        success: false,
        message: '好友请求不存在或已处理'
      })
    }

    if (operation === 'accept') {
      // 开启事务处理接受好友请求
      await prisma.$transaction([
        // 更新好友请求状态
        prisma.friendRequest.update({
          where: { id: requestId },
          data: { status: 'accepted' }
        }),
        // 创建好友关系
        prisma.friend.create({
          data: {
            senderId: friendRequest.senderId,
            receiverId: friendRequest.receiverId,
            status: 'accepted'
          }
        })
      ])

      return NextResponse.json({
        success: true,
        message: '已接受好友请求'
      })
    } else if (operation === 'reject') {
      // 拒绝好友请求
      await prisma.friendRequest.update({
        where: { id: requestId },
        data: { status: 'rejected' }
      })

      return NextResponse.json({
        success: true,
        message: '已拒绝好友请求'
      })
    } else {
      return NextResponse.json({
        success: false,
        message: '无效的操作'
      })
    }
  } catch (error) {
    console.error('Handle friend request failed:', error)
    return NextResponse.json(
      {
        success: false,
        message: '处理好友请求失败'
      },
      { status: HttpStatus.INTERNAL_SERVER_ERROR }
    )
  }
}
